<?php
/**
 * Created by PhpStorm.
 * User: 57124
 * Date: 2022/2/21
 * Time: 14:37
 */

namespace app\util;


use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

class Tools{
    //1、Token 的生成
    public function createToken($username = null){
        $key = md5(TOKEN_KEY);
        $payload=array(
            "iss"=>"空山新雨后",   //签发组织
            "aud"=>"Coala",//签发作者
            'appId'=> "xr571247942",
            'iat'=> time(),
            'exp'=> time() + TOKEN_TIME_YEAR, //一天：86400  七天：604800  一年366：31622400
            "username" => $username,
        );
        $jwt = new JWT();
        $token = $jwt::encode($payload,$key,'HS256');
        return $token;
    }
    //2、Token 的验证 (登录验证需要)
    function checkToken($token){
        $key = md5(TOKEN_KEY);
        try{
            $res = json_encode(JWT::decode($token,$key,['HS256']));
            $arr = json_decode($res,true);
            if(!empty($arr["username"])){
                return ["msg"=>"Token通过","status"=>"success","username"=>$arr["username"],"code"=>200];
            }else{
                return ["msg"=>"当前用户不存在","status"=>"fail","code"=>401];
            }
        }catch (SignatureInvalidException $e){
            return ["msg"=>"Token无效","status"=>"fail","code"=>405,"url"=>"/auth/admin/login"];
        }catch (ExpiredException $e) {
            return ["msg"=>"Token过期","status"=>"fail","code"=>406,"url"=>"/auth/admin/login"];
        }
    }
    // 创建自定义日志文件
    public function createLogFile(){
        //$filePath = App::getRootPath()."public/logs/".date("Ym").".log";
        $dirName = getcwd()."/logs";
        if(!file_exists($dirName)){
            mkdir($dirName,0777,true);
        }
        $filePath = $dirName."/".date("Ym").".log";
        if(!file_exists($filePath)){
            fopen($filePath,"w");
        }
        return $filePath;
    }
    // 加密
    public function encrypt($str){
        if($str){
            $method = "DES-ECB";
            $key ="jingfeng_zhisha";
            $str = openssl_encrypt($str, $method, $key);
        }
        return $str;
    }
    // 解密
    public function decrypt($str){
        if($str) {
            $method = "DES-ECB";
            $key = "jingfeng_zhisha";
            $str = openssl_decrypt($str, $method, $key);
        }
        return $str;
    }

    /**
     * 产生六位（0-9、a-z混合）的随机数
     */
    public function getRand($num){
        if($num < 3){$num = 3;}
        $letters = range('a', 'z');
        $arr = array_merge(range(0, 9), $letters);
        shuffle($arr);//打乱数组
        $str = '';
        $len = count($arr);
        for ($i = 0; $i < $num; $i++){
            $rand = mt_rand(0, $len - 1);//mt_rand() 比rand() 快四倍
            $str .= $arr[$rand];
        }
        return $str;
    }

    // url与参数拼接
    public function joinParams($url,$params = null){
        if (!empty($params)) {
            $url = $url . '?';
            foreach ($params as $key => $val) {
                $url .= $key . '=' . $val . '&';
            }
            $url = substr($url, 0, -1);
        }
        return $url;
    }
    // get 请求
    public function curl_get($url){
        $geturl = $url;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $geturl);//设置提交的url
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   //参数为1表示传输数据，为0表示直接输出显示。
        curl_setopt($curl, CURLOPT_HEADER, 0);//参数为0表示不带头文件，为1表示带头文件
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //如果接口URL是https的,我们将其设为不验证,如果不是https的接口,这句可以不用加
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($curl);//执行命令
        curl_close($curl);
        return $output;  //print_r($output);
    }
    //post请求方法
    public function curl_post($url,$post_data){
        //$post_data = file_get_contents($url,$post_data);//封装内容 路径+ 参数列表
        $post_data = json_encode($post_data);//转成json数据
        $curl = curl_init(); //1.初始化curl句柄
        curl_setopt($curl, CURLOPT_URL, $url);  //设置访问url
        curl_setopt($curl, CURLOPT_POST, 1);//设置post方式提交
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);//设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); //发送POST请求时传递的参数
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($post_data))); //设置头信息
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);//返回值获取数据
        $return_content = curl_exec($curl);     //3.执行curl_exec($curl)
        curl_close($curl);    //4.关闭curl// $curl = 'https://account.teambition.com';
        return $return_content;
    }
}